package com.lxc.lib.net.http

import android.util.Log
import com.lxc.lib.net.storage.BaseResponse
import retrofit2.Response

/**
 *@author: xuancai.Liu
 *@create: 2021-09-10 11:27
 *@program: NetWorkDemo
 *@description:
 */
object RequestHelper {
    private val TAG = "RequestDataManager"

    /**
     * 获取对应retrofit请求
     * baseApi 可做进一步封装
     */
    inline fun <reified T : Any> getApi(baseUrl: String): T {
        return LxcRetrofitFactory.retrofit(baseUrl)
            .create(T::class.java)
    }

    fun <T> requestData(response: Response<T>?, errmsg: String? = null): BaseResponse<T> {
        if (response?.isSuccessful == true) {
            val posts = response.body()
            if (posts == null) {
                Log.e(TAG, "code= ${response.code()}  msg=${response.errorBody().toString()}")
                return BaseResponse(response.code(), false, response.errorBody().toString(), null)
            }
            return BaseResponse(response.code(), true, response.message().toString(), posts)
        } else {
            val msg = response?.errorBody() ?: errmsg
            Log.e(TAG, "code= ${response?.code()}  msg=${msg}")
            return BaseResponse(response?.code() ?: -1, false, msg.toString(), null)
        }
    }
}